package com.allen.library.interceptor;

import android.util.Log;

import com.allen.library.base.LangDialogFragment;
import com.czy.basecommon.utils.global.ItrackApp;
import com.czy.basecommon.utils.tools.ActivityTool;


import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class RefreshTokenInterceptor implements Interceptor {
    private LangDialogFragment langDialogFragment;


    public RefreshTokenInterceptor() {
        Log.e("lock","RefreshTokenInterceptor is init");
    }

    private Lock lock = new ReentrantLock();
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        if (response.code() == 402) {


            // first thread will acquire the lock and start the refresh token
            if (lock.tryLock()) {


                try {
                    // this sync call will refresh the token and save it for
                    // later use (e.g. sharedPreferences)
                    if (!ItrackApp.atomicBoolean.get()){
                        Log.e("lock","dialog is init");
                         langDialogFragment = LangDialogFragment.newInstance("1");
                        langDialogFragment.show(ActivityTool.getInstance().getLastActivity().getFragmentManager(),"tag1");
//                        ActivityTool.getInstance().getLastActivity().getFragmentManager().beginTransaction().add(langDialogFragment, "tag1").commitAllowingStateLoss();

                    }

                } catch (Exception exception) {
                    // depending on what you need to do you can logout the user at this
                    // point or throw an exception and handle it in your onFailure callback
                    return response;
                } finally {

                    lock.unlock();
                    return  response;
                }

            } else {

                lock.lock(); // this will block the thread until the thread that is refreshing
                // the token will call .unlock() method
                lock.unlock();
             return  response;
            }
        } else  if (response.code() == 401) {

            // first thread will acquire the lock and start the refresh token
            if (lock.tryLock()) {

                Log.e("lock","refresh token thread holds the lock");
                try {
                    if (!ItrackApp.atomicBoolean.get()){
                        Log.e("lock","dialog is init");

                        langDialogFragment = LangDialogFragment.newInstance("2");
                        langDialogFragment.show(ActivityTool.getInstance().getLastActivity().getFragmentManager(),"tag2");
//                        SMJApp.atomicBoolean.set(true);
//                        ActivityTool.getInstance().getLastActivity().getFragmentManager().beginTransaction().add(langDialogFragment, "tag1").commitAllowingStateLoss();

                    }



                } catch (Exception exception) {
                    // depending on what you need to do you can logout the user at this
                    // point or throw an exception and handle it in your onFailure callback
                    return response;
                } finally {
                    Log.e("lock","refresh token finished. release lock");

                    lock.unlock();
                    return  response;
                }

            } else {
                Log.e("lock","wait for token to be refreshed");
                lock.lock(); // this will block the thread until the thread that is refreshing
                // the token will call .unlock() method
                lock.unlock();
                Log.e("lock","token refreshed. retry request");
                return  response;
            }
        }else {
            return response;
        }
    }
}
